package entity.transformer;

import java.util.List;

import json.JSONArray;
import json.JSONException;
import json.JSONObject;
import entity.GameEntity;
import entity.Position;
import entity.map.FieldEntityMap;

public class FieldEntityMapTransformer
{

	public String getJSON(FieldEntityMap pMap) throws JSONException
	{
		JSONObject json = new JSONObject();
		JSONArray array = new JSONArray();
		int size = pMap.getSize();
		FieldEntityTransformer transformer = new FieldEntityTransformer();
		json.put("size", size);
		for (int i = 1; i < size; i++)
		{
			for (int j = 1; j < size; j++)
			{
				array.put(transformer.getJSON(pMap.getFieldEntity(new Position(
						i, j))));
			}
		}
		json.put("map", array);
		List<GameEntity> gameEntities = pMap.getGameEntitys();
		JSONArray arrayGE = new JSONArray();
		for( int i=0;i<gameEntities.size();i++)
		{
			arrayGE.put(gameEntities.get(0));//TODO
		}
		json.put("ge", arrayGE);
		return json.toString();
	}

	public FieldEntityMap getJSON(String pJson) throws JSONException
	{
		JSONObject json = new JSONObject(pJson);
		int size = json.getInt("size");
		FieldEntityTransformer transformer = new FieldEntityTransformer();
		FieldEntityMap map = new FieldEntityMap(size, size);
		JSONArray array = json.getJSONArray("map");
		for (int i = 1; i < array.length(); i++)
		{
			String oo = (String) array.get(i);
			map.setFieldEntity(transformer.getJSON(oo));
		}
		return map;
	}

}
